/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package daw.controlador;

import daw.bean.Area;
import daw.bean.Ciudad;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import javax.transaction.UserTransaction;

/**
 *
 * @author Fercho
 */
public class ControladorArea extends HttpServlet {
    @PersistenceUnit
    private EntityManagerFactory emf;
    @Resource
    private UserTransaction utx;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
             String operacion = request.getParameter("operacion");

        if(operacion == null){
            throw new ServletException("No se ha definido valor de operación.");
        }else if(operacion.equals("prepararParaAgregar")){
            EntityManager em = emf.createEntityManager();
            List ciudades = em.createNamedQuery("Ciudad.findAll").getResultList();
            em.close();
            request.setAttribute("ciudades", ciudades);
            getServletContext().getRequestDispatcher("/servicio/protegido/addArea.jsp").forward(request, response);
        }else if(operacion.equals("agregar")){
			String nombre = request.getParameter("nom_area");
			String referencia = request.getParameter("referencia");
			int id = Integer.valueOf(request.getParameter("ciudad"));
			try {
				EntityManager em = emf.createEntityManager();
				Ciudad c;
				Area area = new Area();
				area.setNombre(nombre);
				area.setReferencia(referencia);
				utx.begin();
				area.setIdCiudad(c = em.find(Ciudad.class, id));
				em.persist(area);
				utx.commit();
				List ciudades = em.createNamedQuery("Ciudad.findAll").getResultList();
				em.close();
				request.setAttribute("ciudades", ciudades);
				request.setAttribute("mensaje", "Area registrada."+" Ciudad: "+c.getNombre()+ ", Area: "+area.getNombre());
				request.setAttribute("area", area);
				getServletContext().getRequestDispatcher("/servicio/protegido/addArea.jsp").forward(request, response);
			/*}else{
				throw new RuntimeException("Error de inserción");
			} */
			}
			catch (Exception ex) {
				throw new ServletException(ex);
            }
        }else{
            throw new ServletException("Valor de operación no valido.");
        }   

    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
